package com.jse;

import java.util.ArrayList;
import java.util.EnumSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.DispatcherType;
import javax.servlet.FilterRegistration;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;

import org.nutz.ioc.loader.json.JsonLoader;
import org.nutz.json.JsonException;
import org.nutz.lang.util.NutMap;
import org.nutz.log.Log;
import org.nutz.log.Logs;

public class WebXml implements WebApplicationInitializer {

	Log log = Logs.get();

	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Override
	public void init(ServletContext sce) throws ServletException {
		try {
			JsonLoader json = new JsonLoader("web.js");
			Map m = json.getMap();
			NutMap web = new NutMap(m);

			sce.setAttribute("web.js", web);
			List<Object> list = (List<Object>) web.get("xml");
			for (int i = 0; i < list.size(); i++) {
				NutMap xml = NutMap.WRAP((Map<String, Object>) list.get(i));
				if (xml.getString("type").equals("listener")) {
					sce.addListener(xml.getString("class"));
				} else if (xml.getString("type").equals("filter")) {
					FilterRegistration.Dynamic cos = sce.addFilter(xml.getString("name"), xml.getString("class"));
					if (xml.containsKey("init")) {
						ArrayList<LinkedHashMap> inits = (ArrayList<LinkedHashMap>) xml.get("init");
						inits.forEach((v) -> {
							cos.setInitParameter(v.get("name").toString(), v.get("value").toString());
						});
					}
					EnumSet<DispatcherType> es = EnumSet.noneOf(DispatcherType.class);
					if (xml.containsKey("dispatcher")) {
						xml.getList("dispatcher", String.class).forEach((name) -> {
							es.add(DispatcherType.valueOf(name));
						});
					}
					cos.addMappingForUrlPatterns(es, true, xml.getString("url"));
				}
			}
		} catch (JsonException e) {
			log.error("web.js error:" + e);
		}
	}

}
